<?php
/**
 * Created by PhpStorm.
 * User: 87976
 * Date: 2018/1/25
 * Time: 15:30
 */

namespace App\Services\Album;


use App\Abstracts\TemplateAbstract;
use App\Repositories\Album\AlbumGoodsRepository;
use App\Repositories\Goods\GoodsWidRepository;
use App\Services\Goods\GoodsService;

/**
 * Class AlbumGoodsService
 * @package App\Services\Album
 */
class AlbumGoodsService extends TemplateAbstract
{

    /**
     * @var AlbumGoodsRepository
     */
    protected $albumGoodsRepository;

    /**
     * @var GoodsService
     */
    protected $goodsService;

    /**
     * @var GoodsWidRepository
     */
    protected $goodsWidRepository;

    /**
     * AlbumGoodsService constructor.
     * @param AlbumGoodsRepository $albumGoodsRepository
     * @param GoodsService $goodsService
     * @param GoodsWidRepository $goodsWidRepository
     */
    public function __construct(AlbumGoodsRepository $albumGoodsRepository, GoodsService $goodsService, GoodsWidRepository $goodsWidRepository)
    {
        $this->albumGoodsRepository = $albumGoodsRepository;

        $this->goodsService = $goodsService;

        $this->goodsWidRepository = $goodsWidRepository;
    }

    /**
     * @author Jerry
     * @param array $data
     * @return mixed
     */
    public function handle(array $data)
    {
        $goods = $this->getGoods($data);

        $data['goods_list'] = $goods;

        unset($data['album_id']);

        return $data;
    }

    /**
     * @author Jerry
     * @param array $template
     * @return array
     */
    protected function getGoods(array $template)
    {
        $ids = $this->albumGoodsRepository->findAlbumGoodsByTemplateId($template['id']);
        if (empty($ids)) {
            return [];
        }

        $data = [];
        foreach ($ids as $id) {
            $goods = $this->goodsWidRepository->findGoodsWidInfoByGoodsId($id);
            if (empty($goods)) {
                continue;
            }

            $data[] = (array) $goods;
        }

        return $this->goodsService->formatGoodsTransformList($data);
    }
}